<?php

namespace asyncService\lib;

use \Swoole\Table;

class superGlobalVariable  {

	protected $table;

	protected $lock;

	protected $_KEY = "__key__";

	function __construct($string_size = 1024) {
		$this->table = new Table(1);

		$this->_KEY = md5("__key__".time().rand(1,10100));

		$this->table->column("value",Table::TYPE_STRING, $string_size);

		if(!$this->table->create()){
			throw  new \Exception();
		}

		$this->lock = new \swoole_lock(SWOOLE_MUTEX);
	}

	function set($key,$value){
		$this->lock->lock();
		$old_value = $this->_get();

		$old_value[$key] = $value;
		$this->_set($old_value);
		$this->lock->unlock();
	}

	function get($key){

		$this->lock->lock();
		$old_value = $this->_get();
		$this->lock->unlock();

		if(isset($old_value[$key])){
			return $old_value[$key];
		}
		return null;
	}

	function setArrayValue($key,$index,$value){
		$this->lock->lock();

		$old_value = $this->_get();
		if(!isset($old_value[$key])){
			$old_value[$key] = [];
		}
		$old_value_array = $old_value[$key];
		$old_value_array[$index]= $value;
		$old_value[$key] = $old_value_array;
		$this->_set($old_value);

		$this->lock->unlock();
	}

	function pushArray($key,$value){
		$this->lock->lock();

		$old_value = $this->_get();
		if(!isset($old_value[$key])){
			$old_value[$key] = [];
		}
		$old_value_array = $old_value[$key];
		$old_value_array[]= $value;
		$old_value[$key] = $old_value_array;
		$this->_set($old_value);
		$this->lock->unlock();
	}


	protected function _set($value){
		$s = array("value"=>json_encode($value));
		$this->table->set($this->_KEY,$s);
	}

	protected function _get(){
		$old_value = [];
		if($old_row_value = $this->table->get($this->_KEY)){
			if(isset($old_row_value["value"])){
				if(!$old_value = json_decode($old_row_value['value'],true)){
					$old_value = [];
				}
			}
		}
		return $old_value;
	}


}